package com.bsoft.gol.hcs.specialist.dao;

import com.bsoft.gol.hcs.clinical.bean.req.ExamReportItemListReq;
import ctd.controller.exception.ControllerException;
import ctd.persistence.DAOFactory;
import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import com.bsoft.gol.hcs.enumcase.ConditionFilterMethodEnum;
import com.bsoft.gol.hcs.enumcase.FollowTypeEnum;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.transform.Transformers;
import com.bsoft.gol.hcs.specialist.bean.request.GroupChronicRecordQo;
import com.bsoft.gol.hcs.specialist.bean.response.CrucialRecordResponse;
import com.bsoft.gol.hcs.specialist.bean.response.CrucialTimeRecordList;
import com.bsoft.gol.hcs.specialist.bean.response.FactorData;
import com.bsoft.gol.hcs.specialist.bean.response.PatientSearchProcess;
import com.bsoft.gol.hcs.specialist.entity.FollowUpRouteDetailFactorRelation;
import com.bsoft.gol.hcs.specialist.entity.FusIndexResult;
import com.bsoft.gol.hcs.specialist.entity.InspectReportRecordEntity;
import com.bsoft.gol.hcs.specialist.entity.PatientSearchRuleDetail;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.DateUtil;
import com.bsoft.gol.hcs.utils.IndexResultUtils;

import java.util.*;

import static com.bsoft.gol.hcs.enumcase.ConditionFilterMethodEnum.*;

/**
 * 检验报告记录dao
 *
 * @author lanyu
 * @date 2021年10月14日 11:09
 */
public abstract class InspectReportRecordDAO extends HibernateSupportDelegateDAO<InspectReportRecordEntity> {

    @DAOMethod(sql = "from InspectReportRecordEntity where businessType=:businessType and visitId=:visitId")
    public abstract List<InspectReportRecordEntity> queryInspectReportRecordEntityList(@DAOParam("businessType") String businessType, @DAOParam("visitId") String visitId);

    @DAOMethod(sql = "from InspectReportRecordEntity where reportId=:reportId and visitOrganization=:visitOrganization ")
    public abstract InspectReportRecordEntity getInspectReportRecordByReportId(@DAOParam("reportId") String reportId, @DAOParam("visitOrganization") String visitOrganization);

    /**
     * 更新删除标识
     */
    @DAOMethod(sql = "update InspectReportRecordEntity set deleteFlag='1' where  businessId in(:businessIdList) ")
    public abstract void updateDeleteFlag(@DAOParam("businessIdList") List<String> businessIdList);

    /**
     * 查询同步数量
     *
     * @param startTime
     * @param endTime
     * @return
     */
    @DAOMethod(sql = "select count(1) from InspectReportRecordEntity  where  reportTime>=:startTime and reportTime<=:endTime")
    public abstract Long getInspectReportByToday(@DAOParam("startTime") Date startTime, @DAOParam("endTime") Date endTime);

    /**
     * 查询检验数据
     *
     * @param resultDate
     * @return
     */
    @DAOMethod(sql = "from InspectReportRecordEntity where report_time <:resultDate and delete_flag !='1' ")
    public abstract List<InspectReportRecordEntity> queryInspectReportRecordOverdueList(@DAOParam("resultDate") Date resultDate);

    /**
     * 根据检验报告获取患者信息
     *
     * @param patientSearchRuleDetail
     * @param recordStartTime
     * @param recordEndTime
     * @return
     */
    public List<PatientSearchProcess> queryPatientByInspectReportRecord(final PatientSearchRuleDetail patientSearchRuleDetail, final Date recordStartTime,
                                                                        final Date recordEndTime) {
        HibernateStatelessResultAction<List<PatientSearchProcess>> action =
                new AbstractHibernateStatelessResultAction<List<PatientSearchProcess>>() {
                    @Override
                    public void execute(StatelessSession ss) throws Exception {
                        StringBuilder sqlBuilder = new StringBuilder();
                        sqlBuilder.append("SELECT " +
                                "i.NAME AS patientName, " +
                                "i.visit_organization AS organizationId, " +
                                "i.visit_organization_name AS organizationName, " +
                                "i.source_patient_id AS patientId, " +
                                "i.sex AS patientSex, " +
                                "i.age_value AS patientAge, " +
                                "i.business_type AS source, " +
                                "i.id_card AS cardNumber, " +
                                "i.visit_id AS patientNumber, " +
//                                "f.telephone AS telephone, " +
                                "( SELECT GROUP_CONCAT( distinct f.chronic_disease_id ) FROM " +
                                "fus_team_chronic_group_record f WHERE i.id_card = f.card_number and f.apply_status =" +
                                " '1') AS chronicDiseaseIds," +
                                "( SELECT GROUP_CONCAT( distinct f.chronic_disease_name ) FROM " +
                                "fus_team_chronic_group_record f WHERE i.id_card = f.card_number and f.apply_status =" +
                                " '1' ) AS chronicDiseaseName " +
                                "FROM " +
                                "inspect_report_record i " +
//                                "LEFT JOIN fus_team_chronic_group_record f ON i.id_card = f.card_number " +
                                "INNER JOIN inspect_report_routine_detail id ON i.inspect_report_record_id = id" +
                                ".inspect_report_id " +
                                "AND id.test_id =:secondConditionCode ");
                        if (CommonUtils.isNotEmpty(recordStartTime) && CommonUtils.isNotEmpty(recordEndTime)) {
                            sqlBuilder.append(" and i.report_time>=:recordStartTime and i.report_time<= :recordEndTime ");
                        }
                        String secondConditionCode = patientSearchRuleDetail.getSecondConditionCode();
                        //条件筛选方法：1 范围(包含边界) 2 等于 3 大于 4 小于 5 大于等于 6 小于等于，7包含，8不包含 9 Between
                        Byte conditionFilterMethod = patientSearchRuleDetail.getConditionFilterMethod();
                        ConditionFilterMethodEnum methodEnum = getEnumByKey(conditionFilterMethod);
                        //判断指标的结果性质
                        FusIndexResultDAO fusIndexResultDAO =
                                DAOFactory.getDAO(FusIndexResultDAO.class);
                        List<FusIndexResult> results =
                                fusIndexResultDAO.queryFusIndexResultList(secondConditionCode);
                        String indexResultType= "";
                        if (CommonUtils.isNotEmpty(results)) {
                            indexResultType = results.get(0).getIndexResultType();
                        }
                        Byte natureType = Byte.parseByte(indexResultType);

                        if (natureType != null && natureType == 1) {
                            //定量结果
                            switch (methodEnum) {
                                case SCOPE:
                                case BETWEEN:
                                    sqlBuilder.append(" and id.test_result >= :firstKeywordContent");
                                    sqlBuilder.append(" and id.test_result <= :secondKeywordContent");
                                    break;
                                case EQUAL:
                                    sqlBuilder.append(" and id.test_result in (:keywordList");
                                    sqlBuilder.append(")");
                                    break;
                                case GREATER_THAN:
                                    sqlBuilder.append(" and id.test_result > :firstKeywordContent");
                                    break;
                                case LESS_THAN:
                                    sqlBuilder.append(" and id.test_result < :firstKeywordContent");
                                    break;
                                case GREATER_THAN_OR_EQUAL:
                                    sqlBuilder.append(" and id.test_result >= :firstKeywordContent");
                                    break;
                                case LESS_THAN_OR_EQUAL:
                                    sqlBuilder.append(" and id.test_result <= :firstKeywordContent");
                                    break;
                                default:
                                    throw new ControllerException("不合法的运算符");
                            }
                        } else if (natureType != null && natureType == 2) {
                            //定性结果-只会有包含in 和不包含 not in
                            switch (methodEnum) {
                                case CONTAIN:
                                    sqlBuilder.append(" and id.result_qualitative in (:keywordList) ");
                                    break;
                                case NOT_INCLUDED:
                                    sqlBuilder.append(" and id.result_qualitative not in (:keywordList) ");
                                    break;
                                default:
                                    throw new ControllerException("不合法的运算符");
                            }
                        } else {
                            //文本结果-只会有包含like 和不包含 not like
                            switch (methodEnum) {
                                case CONTAIN:
                                    sqlBuilder.append(" and id.result_qualitative like :firstKeywordContent ");
                                    break;
                                case NOT_INCLUDED:
                                    sqlBuilder.append(" and id.result_qualitative not like :firstKeywordContent ");
                                    break;
                                default:
                                    throw new ControllerException("不合法的运算符");
                            }
                        }
                        Query query = ss.createSQLQuery(sqlBuilder.toString());
                        query.setParameter("secondConditionCode",
                                secondConditionCode);
                        if (CommonUtils.isNotEmpty(recordStartTime) && CommonUtils.isNotEmpty(recordEndTime)) {
                            query.setParameter("recordStartTime", DateUtil.dateFormate(recordStartTime, "yyyy-MM-dd"));
                            query.setParameter("recordEndTime", DateUtil.dateFormate(recordEndTime, "yyyy-MM-dd"));
                        }
                        query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                        //第一个关键字内容（注意多个关键字是用英文逗号隔开的）
                        String firstKeywordContent = patientSearchRuleDetail.getFirstKeywordContent();
                        String secondKeywordContent = patientSearchRuleDetail.getSecondKeywordContent();
                        //因为结果有字符串、整数、小数等多种情况，所以在下面，将结果值转成整数和小数，如果能转成功，则执行对应的比较SQL
                        //只有定量才会需要处理这种情况，定性不需要
                        Long longFirstKeyword = null;
                        Long longSecondKeyword = null;
                        Double doubleFirstKeyword = null;
                        Double doubleSecondKeyword = null;
                        List<String> keywordList = new ArrayList<>();
                        List<Long> longKeywordList = new ArrayList<>();
                        List<Double> doubleKeywordList = new ArrayList<>();
                        if (EQUAL.getType().equals(conditionFilterMethod)||CONTAIN.getType().equals(conditionFilterMethod)|| NOT_INCLUDED.getType().equals(conditionFilterMethod)) {
                            String[] strings;
                            if (firstKeywordContent.contains(",")){
                                strings = firstKeywordContent.split(",");
                            }else{
                                strings=new String[1];
                                strings[0]=firstKeywordContent;
                            }

                            boolean longFlag = true;
                            boolean doubleFlag = true;
                            for (String str :
                                    strings) {
                                try {
                                    if (doubleFlag) {
                                        doubleKeywordList.add(Double.valueOf(str));
                                        continue;
                                    }
                                } catch (Exception e1) {
                                    doubleFlag = false;
                                }
                                try {
                                    if (longFlag) {
                                        longKeywordList.add(Long.valueOf(str));
                                        continue;
                                    }
                                } catch (Exception e) {
                                    longFlag = false;
                                }
                                if (!longFlag && !doubleFlag) {
                                    keywordList.add(str);
                                }
                            }
                        } else if (SCOPE.getType().equals(conditionFilterMethod)) {
                            try {
                                doubleFirstKeyword =
                                        Double.valueOf(firstKeywordContent);
                                doubleSecondKeyword =
                                        Double.valueOf(secondKeywordContent);
                            } catch (Exception e) {
                                doubleFirstKeyword = null;
                                doubleSecondKeyword = null;
                                try {
                                    longFirstKeyword = Long.valueOf(firstKeywordContent);
                                    longSecondKeyword = Long.valueOf(secondKeywordContent);
                                } catch (Exception e1) {
                                    longFirstKeyword = null;
                                    longSecondKeyword = null;
                                }
                            }
                        } else {
                            try {
                                doubleFirstKeyword =
                                        Double.valueOf(firstKeywordContent);
                            } catch (Exception e) {
                                doubleFirstKeyword = null;
                                try {
                                    longFirstKeyword = Long.valueOf(firstKeywordContent);
                                } catch (Exception e1) {
                                    longFirstKeyword = null;
                                }
                            }
                        }
                        //条件筛选方法：1 范围(包含边界) 2 等于 3 大于 4 小于 5 大于等于 6 小于等于，7包含，8不包含 9 Between
                        switch (methodEnum) {
                            case SCOPE:
                            case BETWEEN:
                                if (longFirstKeyword != null && longSecondKeyword != null) {
                                    query.setParameter("firstKeywordContent", longFirstKeyword);
                                    query.setParameter("secondKeywordContent", longSecondKeyword);
                                } else if (doubleFirstKeyword != null && doubleSecondKeyword != null) {
                                    query.setParameter("firstKeywordContent", doubleFirstKeyword);
                                    query.setParameter("secondKeywordContent", doubleSecondKeyword);
                                } else {
                                    query.setParameter("firstKeywordContent", firstKeywordContent);
                                    query.setParameter("secondKeywordContent", secondKeywordContent);
                                }
                                break;
                            case CONTAIN:
                            case NOT_INCLUDED:
                                if (natureType != null && natureType == 2) {
                                    if (CommonUtils.isNotEmpty(longKeywordList)) {
                                        query.setParameterList("keywordList", longKeywordList);
                                    } else if (CommonUtils.isNotEmpty(doubleKeywordList)) {
                                        query.setParameterList("keywordList", doubleKeywordList);
                                    } else {
                                        query.setParameterList("keywordList", keywordList);
                                    }
                                } else {
                                    query.setParameter("firstKeywordContent", "%" + firstKeywordContent + "%");
                                }
                                break;
                            case EQUAL:
                                if (CommonUtils.isNotEmpty(longKeywordList)) {
                                    query.setParameterList("keywordList", longKeywordList);
                                } else if (CommonUtils.isNotEmpty(doubleKeywordList)) {
                                    query.setParameterList("keywordList", doubleKeywordList);
                                } else {
                                    query.setParameterList("keywordList", keywordList);
                                }
                                break;
                            case GREATER_THAN:
                            case LESS_THAN:
                            case GREATER_THAN_OR_EQUAL:
                            case LESS_THAN_OR_EQUAL:
                                if (longFirstKeyword != null) {
                                    query.setParameter("firstKeywordContent", longFirstKeyword);
                                } else if (doubleFirstKeyword != null) {
                                    query.setParameter("firstKeywordContent", doubleFirstKeyword);
                                } else {
                                    query.setParameter("firstKeywordContent", firstKeywordContent);
                                }
                                break;
                        }
                        List<Map> list = query.list();
                        List<PatientSearchProcess> voList = new ArrayList<>();
                        if (CommonUtils.isNotEmpty(list)) {
                            for (Map map : list) {
                                voList.add(ConversionUtils.convert(map, PatientSearchProcess.class));
                            }
                        } else {
                            voList = new ArrayList<>();
                        }
                        setResult(voList);
                    }
                };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     * 获取检验的关联指标信息
     *
     * @param qo
     * @return
     */
    public List<CrucialRecordResponse> queryInspectionReportInfo(GroupChronicRecordQo qo) {
        HibernateStatelessResultAction<List<CrucialRecordResponse>> action = new AbstractHibernateStatelessResultAction<List<CrucialRecordResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("SELECT " +
                        " id.test_id as indexType " +
                        "FROM " +
                        " inspect_report_record ir " +
                        " LEFT JOIN inspect_report_routine_detail id ON ir.inspect_report_record_id = id.inspect_report_id where ir.id_card =:idCard ");
                sqlBuilder.append(" and ir.report_time >=:beginTime and ir.report_time <=:endTime group by id.test_id ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("idCard", qo.getIdCard());
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<CrucialRecordResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, CrucialRecordResponse.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    public List<CrucialTimeRecordList> queryInspectionReportTimeInfo(GroupChronicRecordQo qo, String itemCode) {
        HibernateStatelessResultAction<List<CrucialTimeRecordList>> action = new AbstractHibernateStatelessResultAction<List<CrucialTimeRecordList>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("SELECT " +
                        " id.test_id AS indexType, " +
                        " id.test_name as  testName, "+
                        " ir.lab_order_item_name AS indexName, " +
                        " id.test_result as indexResultContent, " +
                        " id.reference_range as refRange, " +
                        " id.test_result as indexValue, " +
                        " ir.report_time as crucialTime ," +
                        " id.result_hint as resultHint " +
                        "FROM " +
                        " inspect_report_record ir " +
                        " inner JOIN inspect_report_routine_detail id ON ir.inspect_report_record_id = id.inspect_report_id  " +
                        "and id.test_id =:itemCode and ir.id_card =:idCard ");
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    sqlBuilder.append(" and ir.report_time >=:beginTime ");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    sqlBuilder.append(" and ir.report_time <=:endTime ");
                }
                sqlBuilder.append("  order by ir.report_time ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("itemCode", itemCode);
                query.setParameter("idCard", qo.getIdCard());
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<CrucialTimeRecordList> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, CrucialTimeRecordList.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    public List<FactorData> executeFactorForRelatedIndicators(FollowUpRouteDetailFactorRelation factorRelation, Date startTime, Date endTime, List<String> patientIdList, Byte isLoopExecute, Long routeDetailId, String followType) {
        HibernateStatelessResultAction<List<FactorData>> action =
                new AbstractHibernateStatelessResultAction<List<FactorData>>() {
                    @Override
                    public void execute(StatelessSession ss) throws Exception {
                        List<FactorData> voList = new ArrayList<>();
                        StringBuilder sqlBuilder = new StringBuilder();
                        sqlBuilder.append("select patientId,indexRecordId,indexCode,indexName ,indexResult,reportTime,dataSource from ( ");
                        //因素内容性质类型，1定量，2定性 3 文本,因素类型为关联指标必填
                        Byte factorNatureType = factorRelation.getFactorNatureType();
                        sqlBuilder.append("SELECT  '1' as dataSource ,a.source_patient_id AS patientId, ");
                        sqlBuilder.append("a.inspect_report_record_id AS indexRecordId, b.test_id AS indexCode, b.test_name AS indexName, ");
                        if (null != factorNatureType && 1 == factorNatureType) {
                            //定量结果
                            sqlBuilder.append("b.test_result AS indexResult, ");
                        } else {
                            //定性结果,文本结果
                            sqlBuilder.append("b.result_qualitative AS indexResult, ");
                        }
                        sqlBuilder.append("a.report_time AS reportTime ");
                        sqlBuilder.append("FROM inspect_report_record AS a LEFT JOIN inspect_report_routine_detail b ");
                        sqlBuilder.append("on a.inspect_report_record_id = b.inspect_report_id ");
                        sqlBuilder.append("where b.test_id = :indexResultId and a.report_time >= :recordStartTime and" +
                                " a.report_time <= :recordEndTime ");

                        //条件筛选方法：1 范围(包含边界) 2 等于 3 大于 4 小于 5 大于等于 6 小于等于，7包含，8不包含 9 Between
                        Byte conditionFilterMethod = Byte.valueOf(factorRelation.getCompareSign());
                        ConditionFilterMethodEnum methodEnum = getEnumByKey(conditionFilterMethod);
                        if (factorNatureType != null && factorNatureType == 1) {
                            //定量结果
                            switch (methodEnum) {
                                case EQUAL:
                                    sqlBuilder.append(" and b.test_result = :factorResultOne");
                                    break;
                                case GREATER_THAN:
                                    sqlBuilder.append(" and b.test_result > :factorResultOne");
                                    break;
                                case LESS_THAN:
                                    sqlBuilder.append(" and b.test_result < :factorResultOne");
                                    break;
                                case GREATER_THAN_OR_EQUAL:
                                    sqlBuilder.append(" and b.test_result >= :factorResultOne");
                                    break;
                                case LESS_THAN_OR_EQUAL:
                                    sqlBuilder.append(" and b.test_result <= :factorResultOne");
                                    break;
                                case SCOPE:
                                case BETWEEN:
                                    sqlBuilder.append(" and b.test_result >= :factorResultOne and b.test_result <= " +
                                            ":factorResultTwo ");
                                    break;
                                default:
                                    throw new ControllerException("不合法的运算符");
                            }
                        } else if (factorNatureType != null && factorNatureType == 2) {
                            //定性结果-只会有包含in 和不包含 not in
                            switch (methodEnum) {
                                case CONTAIN:
                                    sqlBuilder.append(" and b.result_qualitative in (:factorResultList) ");
                                    break;
                                case NOT_INCLUDED:
                                    sqlBuilder.append(" and b.result_qualitative not in (:factorResultList) ");
                                    break;
                                default:
                                    throw new ControllerException("不合法的运算符");
                            }
                        } else {
                            //文本结果-只会有包含like 和不包含 not like
                            switch (methodEnum) {
                                case CONTAIN:
                                    sqlBuilder.append(" and b.result_qualitative like :factorResultOne ");
                                    break;
                                case NOT_INCLUDED:
                                    sqlBuilder.append(" and b.result_qualitative not like :factorResultOne ");
                                    break;
                                default:
                                    throw new ControllerException("不合法的运算符");
                            }
                        }
                        if (CommonUtils.isNotEmpty(patientIdList)) {
                            sqlBuilder.append(" and a.source_patient_id in (:patientIdList)");
                        }
                        sqlBuilder.append(") AS  m ");
                        //循环执行机制 0 不执行 1 执行
                        if (FollowTypeEnum.FUS_SPECIALIST.getType().equals(followType) && null != isLoopExecute && isLoopExecute == 1) {
                            sqlBuilder.append(" LEFT JOIN fus_factor_data_record f  ON f.patient_id = m.patientId   " +
                                    "AND f.route_detail_id = :routeDetailId AND f.index_record_id = m.indexRecordId " +
                                    "WHERE f.id IS NULL  ");
                        }
                        Query query = ss.createSQLQuery(sqlBuilder.toString());

                        if (factorNatureType != null && factorNatureType == 1) {
                            //定量结果
                            if (SCOPE.equals(methodEnum) || BETWEEN.equals(methodEnum)) {
                                query.setParameter("factorResultOne", factorRelation.getFactorResultOne());
                                query.setParameter("factorResultTwo", factorRelation.getFactorResultTwo());
                            } else {
                                query.setParameter("factorResultOne", factorRelation.getFactorResultOne());
                            }
                        } else if (factorNatureType != null && factorNatureType == 2) {
                            //定性结果-只会有包含in 和不包含 not in
                            String[] strings = factorRelation.getFactorResultOne().split(",");
                            List<String> factorResultList = Arrays.asList(strings);
                            query.setParameterList("factorResultList", factorResultList);
                        } else {
                            //文本结果-只会有包含like 和不包含 not like
                            query.setParameter("factorResultOne", "%" + factorRelation.getFactorResultOne() + "%");
                        }

                        query.setParameter("indexResultId", factorRelation.getIndexResultId());
                        query.setParameter("recordStartTime", startTime);
                        query.setParameter("recordEndTime", endTime);
                        if (CommonUtils.isNotEmpty(patientIdList)) {
                            query.setParameterList("patientIdList", patientIdList);
                        }
                        if (FollowTypeEnum.FUS_SPECIALIST.getType().equals(followType) && null != isLoopExecute && isLoopExecute == 1) {
                            query.setParameter("routeDetailId", routeDetailId);
                        }
                        query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                        List<Map> list = query.list();
                        if (CommonUtils.isNotEmpty(list)) {
                            for (Map map : list) {
                                voList.add(ConversionUtils.convert(map, FactorData.class));
                            }
                        } else {
                            voList = new ArrayList<>();
                        }
                        setResult(voList);
                    }
                };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     * 查询检查某个患者 某一个检查小项 一段时间内的数据
     * @param qo
     * @return
     */

    public List<CrucialTimeRecordList> queryInspectionReportList(ExamReportItemListReq qo) {
        HibernateStatelessResultAction<List<CrucialTimeRecordList>> action = new AbstractHibernateStatelessResultAction<List<CrucialTimeRecordList>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("SELECT " +
                        " id.test_id AS indexType, " +
                        " id.test_name as  testName, "+
                        " ir.lab_order_item_name AS indexName, " +
                        " id.test_result as indexResultContent, " +
                        " id.reference_range as refRange, " +
                        " id.test_result as indexValue, " +
                        " ir.report_time as crucialTime ," +
                        " id.result_hint as resultHint " +
                        "FROM " +
                        " inspect_report_record ir " +
                        " inner JOIN inspect_report_routine_detail id ON ir.inspect_report_record_id = id.inspect_report_id  " +
                        "and id.test_id =:itemCode and ir.id_card =:idCard ");
                if (CommonUtils.isNotEmpty(qo.getStartTime())){
                    sqlBuilder.append(" and ir.report_time >=:beginTime ");
                }
                if (CommonUtils.isNotEmpty(qo.getEndTime())){
                    sqlBuilder.append(" and ir.report_time <=:endTime ");
                }
                sqlBuilder.append("  order by ir.report_time ");
                if (CommonUtils.isEmpty(qo.getStartTime())&& CommonUtils.isEmpty(qo.getEndTime())){
                    sqlBuilder.append(" limit 7 ");
                }
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("itemCode", qo.getItemId());
                query.setParameter("idCard", qo.getIdCard());
                if (CommonUtils.isNotEmpty(qo.getStartTime())){
                    query.setParameter("beginTime", qo.getStartTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getEndTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<CrucialTimeRecordList> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, CrucialTimeRecordList.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
}
